<?php

namespace App\Http\Controllers\Common;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use DB;
use Illuminate\Support\Facades\Redis as Redis;

class TrackerController extends Controller
{

    public function index (Request $request)
    {

        $session_id = session_id();
        $datetime = date('Y-m-d H:i:s');
        $openId = $request->input('openId');
        $custID = $request->input('custID');
        $pcustID = $request->input('pcustID');
        $userAgent = $request->server('HTTP_USER_AGENT');
        $cti = $request->input('cti');
        $refer_host = $request->input('refer_host');
        $postID = $request->input('gid', 0);
        $goodsID = 0;

        if( empty($refer_host) && !empty($request->server('HTTP_REFERER')) ){
            preg_match("/^(http:\/\/)?([^\/]+)/i", $request->server('HTTP_REFERER'), $matches);
            $refer_host = $matches[2];
        }

        if( $postID > 0 ){
            $goodsID = Redis::get('GLOBAL_GOODSID_'.$postID);
            if( empty($goodsID) || stristr($goodsID, 'null') ){
                $goods = DB::table('goods_sale_edit')->select('goodsID')->where('postID','=',$postID)->get();
                if( !empty($goods) ){
                    $goodsID = $goods[0]['goodsID'];
                    Redis::set('GLOBAL_GOODSID_'.$postID,$goodsID);
                    Redis::expire('GLOBAL_GOODSID_'.$postID,63072000);
                }
            }
        }

        //系统
        $os = $request->input('os');
        if (empty($os)) {
            if (stripos($userAgent, 'android')) {
                $os = 'android';
            } elseif (stripos($userAgent, 'iphone')) {
                $os = 'ios';
            }
        }

        //浏览器
        $browser = $request->input('browser');
        if (empty($browser)) {
            $browser = false === stripos($userAgent, 'MicroMessenger') ? $userAgent : 'MicroMessenger';
        }

        //没有会员数据，查询会员登录redis数据
        if (empty($custID) || empty($pcustID)) {
            //获取会员登录数据
            $customer = redisTransformation(Redis::get($session_id . 'LOGINSESSION'));
            if ($customer) {
                $pcustID = $customer['pcustID'];
                $custID= $customer['custID'];
            }
        }

        //微信粉丝id
        if (empty($openId)) {
            $openId = redisTransformation(Redis::get($session_id . 'WECHAT_OPENID'));
        }

        if( !empty($pcustID) && !empty($postID) ){
            Redis::sAdd('cust_view_goods_log_'.date('Ymd'), json_encode(array(
                'create_time' => $datetime,
                'pcustID' => $pcustID,
                'postID' => $postID,
                'goodsID' => $goodsID
            ), true));
        }

        $tracker = [
            'create_time' => $datetime,
            'sessionid' => $session_id,
            'pcustID' => $pcustID,
            'custID' => $custID,
            'openId' => $openId,
            'url' => $request->input('url'),
            'host' => $request->input('host'),
            'refer_url' => $request->input('refer_url'),
            'refer_host' => $refer_host,
            'postID' => $postID,
            'goodsID' => $goodsID,
            'ip' => $request->ip(),
            'userAgent' => $browser,
            'os' => $os,
            'province' => $request->input('province'),
            'wx_source' => $request->input('wx_source'),
            'cti' => $cti
        ];

        $redis_index = 'G_WDH_TRACKER_' . date('Ymd');
        Redis::sAdd($redis_index, \GuzzleHttp\json_encode($tracker, true));


        //记录会员最后登录时间信息
        $ttl_a = Redis::ttl($session_id . 'LOGINSESSION');
        $ttl_b = Redis::ttl('TODAY_LOGIN_' . $pcustID);
        if( !empty($pcustID) && (!Redis::exists('TODAY_LOGIN_'.$pcustID) || $ttl_b<$ttl_a) ){
            DB::table('cust_login_log')->insert(
                array(
                    array(
                        'uuid' => makeUuid(),
                        'timeStamp' => $datetime,
                        'creator' => 'system',
                        'createTime' => $datetime,
                        'pcustID' => $pcustID,
                        'dt' => date('Ymd'),
                        'ip' => $request->ip(),
                        'userAgent' => $browser,
                        'os' => $os
                    )
                )
            );
            Redis::set('TODAY_LOGIN_' . $pcustID,1);
            Redis::expire('TODAY_LOGIN_' . $pcustID, $ttl_a);//设置为会员登录剩余时间（秒数）
        }

        return response()->make();

    }

}
